package com.loma.common.utils.ext

import android.widget.ImageView
import com.bumptech.glide.Glide
import com.bumptech.glide.Priority
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.transition.DrawableCrossFadeFactory
import com.loma.common.R
import com.loma.common.utils.util.dpToPx
import jp.wasabeef.glide.transformations.RoundedCornersTransformation

fun ImageView.setPath(path: String) {

    Glide.with(this.context).load(path)

        //缓存策略,跳过内存缓存【此处应该设置为false，否则列表刷新时会闪一下】
        .skipMemoryCache(false)
        //缓存策略,硬盘缓存-仅仅缓存最终的图像，即降低分辨率后的（或者是转换后的）
        .diskCacheStrategy(DiskCacheStrategy.ALL)
        //设置图片加载的优先级
        .priority(Priority.HIGH)
        .placeholder(R.drawable.placeholder)
        .error(R.drawable.img404)
        .into(this)


}

fun ImageView.loadImage(url: String?, imageOptions: ImageOptions? = null) {
    Glide.with(context)
            .load(url)
            .apply(requestOptions(imageOptions))
            .transition(
                    DrawableTransitionOptions.with(
                            DrawableCrossFadeFactory
                                    .Builder(300)
                                    .setCrossFadeEnabled(true)
                                    .build()
                    )
            )
            .into(this)
}


fun ImageView.loadRoundedCorners(url: String?, imageOptions: ImageOptions? = null) {
    Glide.with(context)
            .load(url)
            .apply(requestOptions(imageOptions))
            .transition(
                    DrawableTransitionOptions.with(
                            DrawableCrossFadeFactory
                                    .Builder(300)
                                    .setCrossFadeEnabled(true)
                                    .build()
                    )
            )
            .into(this)
}

private fun requestOptions(imageOptions: ImageOptions?) = RequestOptions().apply {
    imageOptions?.let {
        transform(RoundedCornersTransformation(it.cornersRadius, 0))
        placeholder(it.placeholder)
        error(it.error)
        fallback(it.fallback)
        if (it.circleCrop) {
            circleCrop()
        }
    }
}

class ImageOptions {
    var placeholder = 0         // 加载占位图
    var error = 0               // 错误占位图
    var fallback = 0            // null占位图
    var cornersRadius = 0       // 圆角半径
    var circleCrop = false      // 是否裁剪为圆形
}
